package com.crane.api.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.crane.common.core.dto.ApiRequest;
import com.crane.common.core.dto.MultiNoTotalResponse;
import com.crane.common.core.dto.Response;
import com.crane.common.core.enums.ConstantEnums;
import com.crane.common.core.utils.CollectionUtil;
import com.crane.common.framework.utils.DateUtil;
import com.crane.common.framework.utils.Jackson2JsonUtil;
import com.crane.common.framework.utils.SignUtil;
import com.crane.oss.api.bean.request.SchoolRequest;
import com.crane.oss.api.bean.request.SchoolStateRequest;
import com.crane.oss.api.bean.resp.StudentClassResp;
import com.crane.oss.api.bean.resp.*;
import com.crane.oss.enums.PartyTypeEnum;
import com.crane.oss.enums.SectionEnum;
import com.crane.oss.school.bean.request.*;
import com.crane.oss.school.bean.resp.*;
import com.crane.oss.school.service.*;
import com.crane.oss.sys.bean.request.party.QueryPartyRequest;
import com.crane.oss.sys.bean.resp.PartyBean;
import com.crane.oss.sys.service.PartyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author bealon
 */
@RestController
@RequestMapping("/api")
public class AppApiController {

    private static final Logger logger = LoggerFactory.getLogger(AppApiController.class);

    @Resource
    PartyService partyService;

    @Resource
    AreaService areaService;

    @Resource
    ClassesInfoService classesInfoService;

    @Resource
    StudentService studentService;

    @Resource
    TeacherService teacherService;

    @Resource
    TeacherCycleService teacherCycleService;


    @PostMapping("/basic/school")
    public MultiNoTotalResponse<SchoolResp> getSchool(@RequestBody @Valid ApiRequest request) {
        logger.info("getSchool req={}", Jackson2JsonUtil.toString(request));
        if (!validate(request)) {
            return MultiNoTotalResponse.buildFailure("签名错误");
        }
        QueryPartyRequest queryPartyRequest = new QueryPartyRequest();
        queryPartyRequest.setPageSize(10000);
        queryPartyRequest.setPartyType(PartyTypeEnum.SCHOOL.getType());
        queryPartyRequest.setStatus(ConstantEnums.STATUS.VALID.getValue());
        IPage<PartyBean> page = partyService.queryList(queryPartyRequest);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<SchoolResp> respList = page.getRecords().stream().map(s -> {
                SchoolResp schoolResp = new SchoolResp();
                schoolResp.setId(s.getPartyId().toString());
                schoolResp.setSchoolName(s.getNameCn());
                schoolResp.setSchoolCode(s.getPartyCode());
                return schoolResp;
            }).collect(Collectors.toList());
            return MultiNoTotalResponse.of(respList);
        } else {
            return MultiNoTotalResponse.of(new ArrayList<>());
        }
    }


    @PostMapping("/basic/schoolAudit")
    public Response schoolAudit(@RequestBody @Valid SchoolStateRequest request) {
        logger.info("schoolAudit req={}", Jackson2JsonUtil.toString(request));
        if (!validate(request)) {
            return Response.buildFailure("签名错误");
        }
        PartyBean partyBean = partyService.queryParty(Long.valueOf(request.getSchoolId()));
        if (null == partyBean) {
            return Response.buildFailure("机构不存在");
        }
        if (request.getState() == 0) {
            logger.error("schoolAudit fail req={}", Jackson2JsonUtil.toString(request));
            partyService.updateSchoolState(1L, ConstantEnums.STATUS.FREZON.getValue());
        }
        return Response.buildSuccess();
    }

    @PostMapping("/basic/campus")
    public MultiNoTotalResponse<SchoolAreaResp> getSchoolArea(@RequestBody @Valid SchoolRequest request) {
        logger.info("getSchoolArea req={}", Jackson2JsonUtil.toString(request));
        if (!validate(request)) {
            return MultiNoTotalResponse.buildFailure("签名错误");
        }
        QueryAreaReq query = new QueryAreaReq();
        query.setPageSize(10000);
        query.setPartyId(Long.valueOf(request.getSchoolId()));
        IPage<AreaResp> page = areaService.queryList(query);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<SchoolAreaResp> respList = page.getRecords().stream().map(s -> {
                SchoolAreaResp r = new SchoolAreaResp();
                r.setId(s.getSchoolId().toString());
                r.setName(s.getAreaName());
                return r;
            }).collect(Collectors.toList());
            return MultiNoTotalResponse.of(respList);
        } else {
            return MultiNoTotalResponse.of(new ArrayList<>());
        }
    }

    @PostMapping("/basic/class")
    public MultiNoTotalResponse<ClassInfoResp> getClassInfo(@RequestBody @Valid SchoolRequest request) {
        logger.info("getClassInfo req={}", Jackson2JsonUtil.toString(request));
        if (!validate(request)) {
            return MultiNoTotalResponse.buildFailure("签名错误");
        }
        QueryClassesInfoReq query = new QueryClassesInfoReq();
        query.setPageSize(10000);
        query.setPartyId(Long.valueOf(request.getSchoolId()));
        IPage<ClassesInfoResp> page = classesInfoService.queryList(query);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<ClassInfoResp> respList = page.getRecords().stream().map(s -> {
                ClassInfoResp r = new ClassInfoResp();
                r.setId(s.getClassId().toString());
                r.setName(s.getClassName());
                r.setPhase(SectionEnum.getAlias(s.getSection()));
                r.setGrade(s.getGrade().toString());
                Integer xdGrade = s.getGrade();
                if (xdGrade > 6 && xdGrade <= 9) {
                    xdGrade = xdGrade - 6;
                } else if (xdGrade > 9) {
                    xdGrade = xdGrade - 9;
                }
                r.setXdGrade(xdGrade.toString());
                r.setType(s.getType().toString());
                r.setCampusId(s.getSchoolId().toString());
                return r;
            }).collect(Collectors.toList());
            return MultiNoTotalResponse.of(respList);
        } else {
            return MultiNoTotalResponse.of(new ArrayList<>());
        }
    }

    @PostMapping("/basic/student")
    public MultiNoTotalResponse<StudentResponse> getStudent(@RequestBody @Valid SchoolRequest request) {
        logger.info("getStudent req={}", Jackson2JsonUtil.toString(request));
        if (!validate(request)) {
            return MultiNoTotalResponse.buildFailure("签名错误");
        }
        QueryStudentReq query = new QueryStudentReq();
        query.setPageSize(10000);
        query.setPartyId(Long.valueOf(request.getSchoolId()));
        IPage<StudentResp> page = studentService.queryStudentClassList(query);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<StudentResponse> respList = page.getRecords().stream().map(s -> {
                StudentResponse r = new StudentResponse();
                r.setId(s.getStudentId().toString());
                r.setName(s.getName());
                r.setSchoolNumber(s.getSn());
                r.setCountryNumber(s.getNumber().toString());
                r.setGender(s.getSex() == 0 ? "1" : "2");
                if (null != s.getBirthday()) {
                    r.setBirthDate(DateUtil.format(DateUtil.TIME_PATTERN, s.getBirthday()));
                }
                r.setPhone("");
                return r;
            }).collect(Collectors.toList());
            return MultiNoTotalResponse.of(respList);
        } else {
            return MultiNoTotalResponse.of(new ArrayList<>());
        }
    }

    @PostMapping("/basic/refStudentClass")
    public MultiNoTotalResponse<StudentClassResp> getStudentClass(@RequestBody @Valid SchoolRequest request) {
        logger.info("getStudentClass req={}", Jackson2JsonUtil.toString(request));
        if (!validate(request)) {
            return MultiNoTotalResponse.buildFailure("签名错误");
        }
        QueryStudentReq query = new QueryStudentReq();
        query.setPageSize(20000);
        query.setPartyId(Long.valueOf(request.getSchoolId()));
        IPage<StudentResp> page = studentService.queryStudentClassList(query);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<StudentClassResp> respList = page.getRecords().stream().map(s -> {
                StudentClassResp r = new StudentClassResp();
                r.setStudentId(s.getStudentId().toString());
                r.setClassId(s.getClassId().toString());
                r.setClassType(s.getType().toString());
                return r;
            }).collect(Collectors.toList());
            return MultiNoTotalResponse.of(respList);
        } else {
            return MultiNoTotalResponse.of(new ArrayList<>());
        }
    }

    @PostMapping("/basic/teacher")
    public MultiNoTotalResponse<TeacherResponse> getTeacher(@RequestBody @Valid SchoolRequest request) {
        logger.info("getTeacher req={}", Jackson2JsonUtil.toString(request));
        if (!validate(request)) {
            return MultiNoTotalResponse.buildFailure("签名错误");
        }
        QueryTeacherReq query = new QueryTeacherReq();
        query.setPageSize(10000);
        query.setPartyId(Long.valueOf(request.getSchoolId()));
        IPage<TeacherResp> page = teacherService.queryList(query);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<TeacherResponse> respList = page.getRecords().stream().map(s -> {
                TeacherResponse r = new TeacherResponse();
                r.setId(s.getTeacherId().toString());
                r.setName(s.getName());
                r.setAccount(teacherService.getPinyin(s.getName(), s.getTeacherId()));
                String password = "zhty" + s.getPhone().substring(s.getPhone().length() - 4);
                r.setPassword(password);
                r.setStaffNumber("");
                r.setRole(s.getType().toString());
                r.setGender(s.getSex() == 0 ? "1" : "2");
                r.setCampusId(s.getSchoolId().toString());
                return r;
            }).collect(Collectors.toList());
            return MultiNoTotalResponse.of(respList);
        } else {
            return MultiNoTotalResponse.of(new ArrayList<>());
        }
    }

    @PostMapping("/basic/teachCycle")
    public MultiNoTotalResponse<TeachCycleResp> getTeachCycle(@RequestBody @Valid SchoolRequest request) {
        logger.info("getTeachCycle req={}", Jackson2JsonUtil.toString(request));
        if (!validate(request)) {
            return MultiNoTotalResponse.buildFailure("签名错误");
        }
        QueryTeacherCycleReq query = new QueryTeacherCycleReq();
        query.setPageSize(10000);
        query.setPartyId(Long.valueOf(request.getSchoolId()));
        IPage<TeacherCycleResp> page = teacherCycleService.queryList(query);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<TeachCycleResp> respList = page.getRecords().stream().map(s -> {
                TeachCycleResp r = new TeachCycleResp();
                r.setId(s.getId().toString());
                r.setName(s.getCycleName());
                r.setBeginDate(DateUtil.format(DateUtil.TIME_PATTERN, s.getCycleStartTime()));
                r.setEndDate(DateUtil.format(DateUtil.TIME_PATTERN, s.getCycleEndTime()));
                r.setTermNumber(s.getSemester());
                return r;
            }).collect(Collectors.toList());
            return MultiNoTotalResponse.of(respList);
        } else {
            return MultiNoTotalResponse.of(new ArrayList<>());
        }
    }

    private boolean validate(ApiRequest request) {
        if (!request.getAppKey().equals("kedaxunfei")) {
            return true;
        }
        return request.getSign().equals(SignUtil.getSign(request, "123456"));
    }

    public static void main(String[] args) {
        SchoolRequest apiRequest = new SchoolRequest();
        apiRequest.setAppKey("kedaxunfei");
        apiRequest.setDt(System.currentTimeMillis());
        apiRequest.setSchoolId("87");
        apiRequest.setSign(SignUtil.getSign(apiRequest, "123456"));
        System.out.println(JSONUtil.toJsonStr(apiRequest));
    }
}
